package com.hs.authcenter.enhancer;

import com.hs.authcenter.entity.UserDetailsWrap;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 对JWT生成的token进行增强
 * @Author 胡尚
 * @Date: 2024/7/26 15:14
 */
public class JwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        // 该对象就是我们自定义HushangUserDetailsService 返回的UserDetails对象
        UserDetailsWrap userDetails = (UserDetailsWrap)authentication.getPrincipal();

        final Map<String, Object> additionalInfo = new HashMap<>();
        final Map<String, Object> retMap = new HashMap<>();

        //todo 这里暴露UserId到Jwt的令牌中,后期可以根据自己的业务需要 进行添加字段
        additionalInfo.put("userId",userDetails.getUser().getId());
        additionalInfo.put("userName",userDetails.getUser().getUsername());

        retMap.put("additionalInfo", additionalInfo);

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(retMap);

        return accessToken;
    }
}
